package com.david.appletree

import android.graphics.*
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.*
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.david.core.event.MyEventBus
import com.david.core.event.Subscribe
import com.david.core.event.ThreadMode
import com.david.core.imgloader.ImageDownLoader
import com.david.core.imgloader.LruImageLoader
import com.david.core.utils.DpUtils
import com.david.core.utils.PosterCreator
import com.david.core.view.ColorPickerView
import com.david.core.view.JustifyTextView
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.io.File
import java.lang.Runnable
import java.net.URL


class MainActivity : AppCompatActivity() {
    suspend fun test()= flow<Int> {
            for (i in 0 until 1) {
                Log.e("flow", "for " + Thread.currentThread().name)
                emit(i)
            }
        }.flowOn(Dispatchers.IO)

    suspend fun request() = flow<String> {
//        emit()
    }


//        flow {
//            for (i in 1..5) {
//                delay(100)
//                emit(i)
//            }
//        }.map {
//            it * it
//        }.flowOn(Dispatchers.IO)
//            .collect {
//                println(it)
//            }
//
    var channelList:ArrayList<String> = ArrayList();
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        if (BuildConfig.DEBUG){
            ARouter.openLog();
            ARouter.openDebug();
        


        ARouter.init(application)

        Glide.with(this).downloadOnly()
            .apply(RequestOptions.bitmapTransform(BlurTransformation(25))) // 设置高斯模糊效果，25为模糊半径，3为模糊迭代次数
        .load("https://pic2.zhimg.com/v2-757a1279765e3ff8f8688a6be5e8527c_720w.webp?source=d6434cab")
            .listener(object: RequestListener<File>{

                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File>, isFirstResource: Boolean): Boolean {
                    return true
                }

                override fun onResourceReady(resource: File, model: Any, target: Target<File>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                    return true
                }

            }).preload()

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)



//        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
//        getSupportActionBar()?.hide();// 隐藏ActionBar
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//remove notification bar  即全屏


        setContentView(R.layout.activity_main)
        val testModel = ViewModelProvider(this).get(TestModel::class.java)
//        testModel.test()



        runBlocking{
            test().
            onStart {
                Log.e("flow", "onStart " + Thread.currentThread().name)
            }
                .onCompletion {
                    Log.e("flow", "onCompletion" + Thread.currentThread().name)
                }
                .collect {
                    Log.e("flow", "collect " + Thread.currentThread().name)
                }
        }



        LruImageLoader.getInstance().init(application)

        for (i in 0..50) {
            channelList.add("中央$i 套")
        }


        val video_view = findViewById<VideoView>(R.id.video_view)
        video_view?.let { video->
            video.setVideoURI(Uri.parse(""))
            video.start()
        }


        val job = GlobalScope.launch(Dispatchers.IO, CoroutineStart.LAZY){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        job.start()
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }

//        CoroutineScope(application).launch(Dispatchers.IO){
//            Log.e("coroute", "thread:"+ Thread.currentThread().name)
//        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
        GlobalScope.launch(Dispatchers.IO){
            Log.e("coroute", "thread:"+ Thread.currentThread().name)
        }
//        video_view.setVideoPath("https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")
        video_view.setVideoPath("rtsp://192.168.8.138:554/cam/realmonitor?channel=1&subtype=0&unicast=true&proto=Onvif")

//        video_view.start()
        video_view.setOnPreparedListener(object :MediaPlayer.OnPreparedListener{
            override fun onPrepared(mp: MediaPlayer?) {
                video_view.requestFocus()
                video_view.start()
            }

        })

        video_view.setOnErrorListener(object :MediaPlayer.OnErrorListener{
            override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
                Log.e("video", what.toString() + ":" + extra)
                return false
            }

        })
        val channels = findViewById<RecyclerView>(R.id.channels)
        channels.layoutManager = LinearLayoutManager(this)

        channels.adapter = ChannelAdapter()

        val webview = findViewById<WebView>(R.id.webview)
        webview.webChromeClient = object :WebChromeClient(){

        }

        webview.webViewClient = object :WebViewClient(){

        }


        val color_picker_view = findViewById<ColorPickerView>(R.id.color_picker_view)
        color_picker_view.setOnColorChangedListener(object :
            com.david.core.view.ColorPickerView.OnColorChangedListener{
            override fun onColorChange(hsb: FloatArray?) {
                Log.e("color", "hsb:" + (hsb?.get(0) ?: "") +":"+ (hsb?.get(1) ?: "") +":"+ (hsb?.get(2) ?: ""))
            }

        })

        val find_onvif = findViewById<JustifyTextView>(R.id.find_onvif)
        find_onvif.postDelayed(Runnable {
            if ((find_onvif.width % find_onvif.textSize) > 5f) {
                find_onvif.width = ((find_onvif.width / find_onvif.textSize) * find_onvif.textSize).toInt()
            }
        }, 2000)
//        find_onvif.setText(Html.fromHtml("测试时间是测试时间是断电测试时间是嗯嗯北包包，测试时间是泰国广告图。\\n\n" +
//                "  嘀嘀打车测试时间是测试时间是断电测试时间是是嗯嗯北包包，测试时间是泰国广告，。得到的测试时间是测试时间是断电测试时间是嗯嗯北包包，测试时间是泰国广告图。\\n\n" +
//                "  嘀嘀打车测试时间的是测试时间是断电测试时间是是嗯嗯北包包，测试时间是泰国广告，。得到的"))


//        var webview = findViewById<com.tencent.smtt.sdk.WebView>(R.id.webview)
//        webview.webChromeClient = com.tencent.smtt.sdk.WebChromeClient()
//        webview.webViewClient = com.tencent.smtt.sdk.WebViewClient()
//        webview.loadUrl("https://divaid.github.io/htmlminifuncs/books/%E4%B8%80%E7%A2%97%E6%B8%85%E6%B1%A4%E8%8A%A5%E9%BA%A6%E9%9D%A2.pdf")

        findViewById<View>(R.id.register).setOnClickListener {

//            LruImageLoader.getInstance().createBuilder().setImageView(image).setTag("main").setUrl("https://img-bss.csdn.net/1636699890948.png")
//                .startLoad()
//            LruImageLoader.getInstance().pauseLoad("main")
//            LruImageLoader.getInstance().createBuilder().setLoadImgId(R.mipmap.ic_launcher).setImageView(image1).setTag("main").setUrl("https://img-bss.csdn.net/1635839557569.jpg")
//                .startLoad()
//            Glide.with(this).load("https://segmentfault.com/img/remote/1460000040966057").into(image)

//            runBlocking {
//                //主线程
//
//                launch {
//                    //当前在主协程(默认)
//                    Log.e("main", "launch thread:" + Thread.currentThread().name)
//                }
//
//                launch(Dispatchers.IO) {
//                    //这个括号中的消息在子线程中
//                    Log.e("main", "launch Dispatchers.IO thread:" + Thread.currentThread().name)
//
//                    withContext(Dispatchers.Main){
//
//                    }
//                    //重复执行
//                    repeat(3) {
//                        Log.e("main", "launch Dispatchers.IO repeat thread:" + Thread.currentThread().name)
//                        //等待1s
//                        delay(1000)
//                    }
//                }
//            }


            ARouter.getInstance()
                .build("/page/router")
//                .withString("path","您好")
                .navigation();


            // Check whether has the write settings permission or not.
            // Check whether has the write settings permission or not.
//            val settingsCanWrite: Boolean = Settings.System.canWrite(this@MainActivity)
//            if (!settingsCanWrite) {
//                // If do not have write settings permission then open the Can modify system settings panel.
//                val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
//                startActivity(intent)
//            } else {
//                // If has permission then show an alert dialog with message.
//                val alertDialog: AlertDialog =
//                    AlertDialog.Builder(this@MainActivity).create()
//                alertDialog.setMessage("You have system write settings permission now.")
//                alertDialog.show()
//            }
//            MyEventBus.getDefault().register(this, "testSubMethod", TestEvent::class.java)

//            UrlHttpRequest().getRequest("https://divaid.github.io/htmlminifuncs/","",object :UrlHttpResponse{
//                override fun onSuccess(result: String) {
//                    ToastUtils.instance.toast("onSuccess")
//                }
//
//                override fun onFail(msg: String) {
//
//                }
//
//            })
            MyEventBus.getDefault().register(this)
//            var file = File(Environment.getExternalStorageDirectory().absolutePath + "/DingTalk/test1.jpg")
//            BitmapUtils.compressImage(file.absolutePath, Environment.getExternalStorageDirectory().absolutePath + "/test.jpg", 1)


//            var options = BitmapFactory.Options()
//            options.inJustDecodeBounds = true
//            BitmapFactory.decodeFile(file.absolutePath, options)
//
//            options.inJustDecodeBounds = false
//            if (options.outWidth > 1080) {//宽大于1080则尺寸也缩为二分之一
//                options.inSampleSize = 2
//            }
//
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                options.outConfig = Bitmap.Config.RGB_565
//            }
//
//            var bitmap =BitmapFactory.decodeFile(file.absolutePath, options)
//            BitmapUtils.saveBitmap("test.jpg", bitmap, this)




            ImageDownLoader.getInstance().init(application)
            ImageDownLoader.getInstance().downloadImage("https://mdapi.4yankj.cn/mediainfo3/get/1763844", object :
                ImageDownLoader.OnImageDownLoadListener{
                override fun onImageDownLoad(filePath: String?) {
                    Log.e("image", "onImageDownLoad " + filePath)
                }

                override fun onImageDownLoadError(error: String?, url: String?) {
                    Log.e("image", "onImageDownLoadError " + error)
                }

            })
        }

        findViewById<View>(R.id.unregister).setOnClickListener {
            LruImageLoader.getInstance().resumeLoad("main")
            MyEventBus.getDefault().unregister(this, "testSubMethod", TestEvent::class.java)
        }

        findViewById<View>(R.id.post).setOnClickListener {
            MyEventBus.getDefault().post(TestEvent())
        }

//        val bg = BitmapFactory.decodeResource(resources, R.drawable.bg)
//        val avatar = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_round)
//        val avatarLabel = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_round)
//        val nameLabel = BitmapFactory.decodeResource(resources, R.drawable.my_ic_deposit)
//        val qrImg = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher)
//        val text = BitmapFactory.decodeResource(resources, R.drawable.my_ic_text)
//        val bitmap = PosterCreator.Builder()
//            .setDesignWidth(1125)
//            .setDesignHeight(2436)
//            .addRect(Color.WHITE, Paint.Style.FILL, 0f, RectF(0F, 2028F, 1125F, 2436F))
//            .addRect(Color.parseColor("#FF5800"), Paint.Style.FILL, 0f, RectF(96f, 2235f, 96f, 2319f))
//            .addImage(bg, Rect(0, 0, bg.width, bg.height), Rect(0, 0, 1125, 2028))
//            .addImage(avatar, Rect(0, 0, avatar.width, avatar.height), Rect(72, 300, 288, 516))
//            .addImage(avatarLabel, Rect(0, 0, avatarLabel.width, avatarLabel.height), Rect(240, 468, 288, 516))
//            .addImage(nameLabel, Rect(0, 0, nameLabel.width, nameLabel.height), Rect(240, 468, 288, 516))
//            .addImage(qrImg, Rect(0, 0, qrImg.width, qrImg.height), Rect(813, 2118, 1035, 2331))
//            .addImage(text, Rect(0, 0, text.width, text.height), Rect(96, 2124, 390, 2196))
//            .addTextBean(Color.parseColor("#24292B"),
//                DpUtils.dp2Px(this, 24f).toFloat(), Paint.Style.FILL, "haha", 336f, false, 390f)
//            .addTextBean(Color.parseColor("#24292B"), DpUtils.dp2Px(this, 18f).toFloat(), Paint.Style.FILL, "2022/3/3", 336f, false, 480f)
//            .create()
//        val bitmap = UserCareImgUtil.getShareBitmap(
//            BitmapFactory.decodeResource(resources, R.drawable.bg),
//            BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_round),
//            BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_round),
//            "haha",
//            BitmapFactory.decodeResource(resources, R.drawable.my_ic_deposit),
//            BitmapFactory.decodeResource(resources, R.drawable.my_ic_text),
//            BitmapFactory.decodeResource(resources, R.drawable.ic_launcher)
//        )


        //Thread(){
        //    kotlin.run {
        //        val bgBitmap = BitmapFactory.decodeStream(URL("https://dm30webimages.geely.com/GeelyPromotion/xyePro/yiqi/xyePro.png").openStream())
        //        val avatarBitmap = BitmapFactory.decodeStream(URL("https://ts3.cn.mm.bing.net/th?q=4K+%e7%be%8e%e5%a5%b3&w=36&h=36&c=7&rs=1&p=0&o=5&dpr=2&pid=1.7&mkt=zh-CN&cc=CN&setlang=zh-Hans&adlt=strict&t=1").openStream())
        //
        //        val bitmap = PosterCreator.Builder().setDesignWidth(660).setDesignHeight(235)
        //            .addImage(bgBitmap, Rect(0, 0, 660, 235), Rect(0, 0, 660, 235))
        //            .addImage(avatarBitmap, Rect(0, 0, 100, 100), Rect(0, 0, 100, 100))
        //            .create()
        //
        //        runOnUiThread {
        //            findViewById<ImageView>(R.id.image_view).setImageBitmap(
        //                bitmap
        //            )
        //        }
        //    }
        //}.start()

        Glide.with(this)
            .load("https://pic2.zhimg.com/v2-757a1279765e3ff8f8688a6be5e8527c_720w.webp?source=d6434cab")
            .apply(RequestOptions.bitmapTransform(BlurTransformation(135))) // 设置高斯模糊效果，25为模糊半径，3为模糊迭代次数
            .into(findViewById(R.id.image_view))

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun testSubMethod(event: TestEvent){
        Toast.makeText(this, "testSubMethod", Toast.LENGTH_LONG).show()
    }

    inner class ChannelAdapter:RecyclerView.Adapter<ChannelHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChannelHolder {
            return ChannelHolder(LayoutInflater.from(this@MainActivity).inflate(R.layout.item_channel, parent, false))
        }

        override fun getItemCount(): Int {
            return channelList.size
        }

        override fun onBindViewHolder(holder: ChannelHolder, position: Int) {

//            https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/3o0yevhsuvfakczm5kozhqe6y6f4
//
//https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/upxvp0qcqdzmj1m72l0tkfnafdga
//
//https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/kdoqdhaqxtp917vjl0it66gz9q41
//
//https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/aa1bjhfo68scmwx37z21crrsjmyb
//
//https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/ridd5nbxtromkktwb05k0qcqfdpe


            if (position == 10) {
                LruImageLoader.getInstance().loadCacheImage("https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/aa1bjhfo68scmwx37z21crrsjmyb",holder.img, "mainPage")

            } else if (position == 11) {
                LruImageLoader.getInstance().loadCacheImage("https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/ridd5nbxtromkktwb05k0qcqfdpe",holder.img, "mainPage")

            }
            when(position % 3) {
                0->{
                    LruImageLoader.getInstance().loadCacheImage("https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/3o0yevhsuvfakczm5kozhqe6y6f4",holder.img, "mainPage")
                }
                1->{
                    LruImageLoader.getInstance().loadCacheImage("https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/upxvp0qcqdzmj1m72l0tkfnafdga",holder.img, "mainPage")
                }
                2->{
                    LruImageLoader.getInstance().loadCacheImage("https://qiping-smartlife-cms.oss-cn-shanghai.aliyuncs.com/cms/kdoqdhaqxtp917vjl0it66gz9q41",holder.img, "mainPage")
                }
            }
//                LruImageLoader.getInstance().loadCacheImage("https://img-home.csdnimg.cn/images/20201231031228.jpg",holder.img)
//            if (position%2==0) {
//                LruImageLoader.getInstance().loadCacheImage("http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?imageMogr2/thumbnail/!50p/format/webp",holder.img)
//
//            } else {
//
//                LruImageLoader.getInstance().loadCacheImage("https://e-share.obs.cn-north-1.myhuaweicloud.com/example.jpg?x-image-process=image/resize,w_200,h_200/imageslim/format,webp",holder.img)
//            }
            holder.title.text = channelList[position]
        }

    }

    override fun onResume() {
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        LruImageLoader.getInstance().onPageDestroy("mainPage")
    }

    class ChannelHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        var img:ImageView = itemView.findViewById(R.id.img)
        var title:TextView = itemView.findViewById(R.id.title)
    }
}
